package com.mkk.deskTopSearch.worker;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

import org.apache.lucene.search.Query;

import com.gh.deskTopSearch.search.FileSearcher;
import com.gh.deskTopSearch.search.SearchTools;
import com.gh.lucene.util.UserData;
import com.gh.lucene.util.search.QuerySession;
import com.mkk.deskTopSearch.util.LogUtil;
import com.mkk.deskTopSearch.util.SearcherManager;

/**
 * 2010-8-10 下午11:08:57
 * 
 * @author mkk 搜索SwingWorker
 */
public class SearchWorker extends SwingWorker<Boolean, Integer> {

	// 搜索关键字
	private String keyWord;
	// 进度条
	private JProgressBar bar;
	// 搜索结果
	private List<UserData> resList;
	// 搜索耗时
	private long times;
	// 保存搜索过程中可能出现的异常信息
	private String errorInfo;

	/**
	 * @param keyWord
	 *            搜索关键字
	 * @param bar
	 *            进度条
	 */
	public SearchWorker(String keyWord, JProgressBar bar) {
		super();
		this.resList = new ArrayList<UserData>();
		this.keyWord = keyWord;
		this.bar = bar;

	}

	/**
	 * 后台事件
	 */
	protected Boolean doInBackground() throws Exception {
		// 不确定模式
		bar.setIndeterminate(true);
		// 显示字符串
		bar.setStringPainted(true);
		bar.setString("搜索 " + keyWord);
		this.bar.setVisible(true);
		long start = System.currentTimeMillis();
		QuerySession querySession = null;
		FileSearcher searcher = null;
		try {
			searcher = SearcherManager.getSearcherManager().getFileSearcher();
			// 默认使用IK查询
			Query query = SearchTools.crreateFileNameQueryAnalyzedByIK(keyWord);
			querySession = searcher.createQuerySession(query);
			querySession.execute();
			int count = 0;
			while (querySession.hasMore()) {
				this.resList.add(querySession.next());
				// this.resList.addAll(querySession.next(PropertiesUtil.SEARCH_RETURN_NUMBER));
				publish(++count);
			}
			// 搜索时间
			this.times = (System.currentTimeMillis() - start);
			// 进度条处理
			// 设置进度条为确定模式
			bar.setIndeterminate(false);
			// 不显示字符串与最大值
			bar.setStringPainted(false);
			bar.setMaximum(count);

		} catch (Exception e) {
			e.printStackTrace();
			this.errorInfo = e.getMessage();
			// 保存异常日志
			LogUtil.saveExceptionLog(e);
			return Boolean.FALSE;
		} finally {
			if (querySession != null) {
				querySession.close();
			}
			// if (searcher != null) {
			// searcher.close();
			// }
		}
		return Boolean.TRUE;
	}

	/**
	 * 中间处理
	 */
	protected void process(List<Integer> chunks) {
		for (int i : chunks) {
			this.bar.setValue(i);
		}
	}

	/**
	 * 完成
	 */
	protected void done() {
		this.bar.setVisible(false);
	}

	/**
	 * 获取错误信息
	 * 
	 * @return
	 */
	public String getErrorInfo() {
		return errorInfo;
	}

	/**
	 * 获取搜索结果
	 * 
	 * @return
	 */
	public List<UserData> getResList() {
		return resList;
	}

	/**
	 * 获取搜索耗时
	 * 
	 * @return
	 */
	public long getTimes() {
		return times;
	}

}
